import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Switch } from '@/components/ui/switch'
import { Textarea } from '@/components/ui/textarea'
import { Badge } from '@/components/ui/badge'
import { Separator } from '@/components/ui/separator'
import { ScrollArea } from '@/components/ui/scroll-area'
import {
  Plus,
  Trash2,
  Play,
  Pause,
  Edit2,
  X,
  Check,
  Volume2,
  Sparkles,
  ChevronDown,
  ChevronUp,
  Timer,
  UserPlus,
  Settings,
  RefreshCw,
  MessageSquareText,
  Trash,
} from 'lucide-react'
import { useAIAssist } from '@/hooks/useAIAssist'
import { useToast } from '@/hooks/useToast'
import { useAutoReply, type EventMessageType } from '@/hooks/useAutoReply'
import { useAccounts } from '@/hooks/useAccounts'
import { useState, useCallback, useMemo, useRef, useEffect } from 'react'
import { IPC_CHANNELS } from 'shared/ipcChannels'
import { useAIChatStore } from '@/hooks/useAIChat'
import type { ProviderConfig, LiveStreamConfigPreset } from '@/hooks/useAIChat'
import type { AIProvider } from '@/hooks/useAIChat'
import { createFrontendLogger } from '@/utils/logger'
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog'
import type { PreviewQueueItem, RecycleBinItem } from '@/hooks/useAIAssist'

// 全局播放管理器（保存定时器和播放锁，不随组件卸载而清除）
interface GlobalPlaybackManager {
  countdownTimer: NodeJS.Timeout | null
  playTimeout: NodeJS.Timeout | null
  isAIReplying: boolean // AI智能回复播放锁（最高优先级）
  interruptedAudio: { // 被打断的音频信息（用于断点续播）
    base64Audio: string
    currentTime: number
  } | null
}

// 使用 window 对象保存全局播放管理器
declare global {
  interface Window {
    __aiAssistPlaybackManager?: GlobalPlaybackManager
  }
}

// 获取或创建全局播放管理器
const getPlaybackManager = (): GlobalPlaybackManager => {
  if (!window.__aiAssistPlaybackManager) {
    window.__aiAssistPlaybackManager = {
      countdownTimer: null,
      playTimeout: null,
      isAIReplying: false,
      interruptedAudio: null,
    }
  }
  return window.__aiAssistPlaybackManager
}

// ✅ 辅助函数：获取消息文本描述
const getMessageText = (message: any): string => {
  switch (message.msg_type) {
    case 'comment':
      return message.content || ''
    case 'room_enter':
      return '进入直播间'
    case 'room_like':
      return '点赞了直播间'
    case 'room_follow':
      return '关注了直播间'
    case 'subscribe_merchant_brand_vip':
      return '加入了品牌会员'
    case 'live_order':
      return message.product_title || '购买商品'
    case 'ecom_fansclub_participate':
      return '加入了粉丝团'
    default:
      return '未知消息'
  }
}

export default function ContentRewriteCard() {
  const { 
    config, 
    updateConfig, 
    contentRewrite,
    isBroadcasting,
    setPreviewQueue: setGlobalPreviewQueue,
    setRecycleBin: setGlobalRecycleBin,
    setCurrentSequentialIndex: setGlobalSequentialIndex,
    setCurrentPlayingId: setGlobalPlayingId,
    setContentRewritePlaying,
  } = useAIAssist()
  const { currentAccountId } = useAccounts()
  const { toast } = useToast()
  const logger = useMemo(() => createFrontendLogger('AI助播'), [])
  const { isListening, comments } = useAutoReply()
  
  // 话术管理相关状态
  const [newScript, setNewScript] = useState('')
  const [editingId, setEditingId] = useState<string | null>(null)
  const [editingContent, setEditingContent] = useState('')
  
  // 一键播报设置
  const [quickPlayMode, setQuickPlayMode] = useState<'immediate' | 'next'>('next') // 一键播报独立的播放模式
  const [showTemplateConfig, setShowTemplateConfig] = useState(false)
  const [templateSequentialIndex, setTemplateSequentialIndex] = useState({ time: 0, welcome: 0 })
  
  // AI生成相关状态
  const [showAIGenerator, setShowAIGenerator] = useState(false)
  const [aiGenerateCount, setAiGenerateCount] = useState(5)
  const [aiGenerateLength, setAiGenerateLength] = useState(50)
  const [aiGenerateStyle, setAiGenerateStyle] = useState('')
  const [aiGenerateExample, setAiGenerateExample] = useState('')
  const [isGenerating, setIsGenerating] = useState(false)

  // 话术列表测试播放状态
  const [testPlayingScriptId, setTestPlayingScriptId] = useState<string | null>(null)

  // 从全局状态获取播放队列相关数据
  const previewQueue = contentRewrite.previewQueue
  const recycleBin = contentRewrite.recycleBin
  const currentSequentialIndex = contentRewrite.currentSequentialIndex
  const currentPlayingId = contentRewrite.currentPlayingId
  
  // 本地UI状态
  const [isPlaying, setIsPlaying] = useState(false)
  const [isLoadingQueue, setIsLoadingQueue] = useState(false)
  const [countdown, setCountdown] = useState(0)
  
  // 使用ref避免闭包问题
  const isPlayingRef = useRef(false)
  const previewQueueRef = useRef<PreviewQueueItem[]>([]) // 追踪最新的队列状态
  const recycleBinRef = useRef<RecycleBinItem[]>([]) // 追踪最新的回收站状态
  const playFirstInQueueRef = useRef<(() => void) | null>(null) // 保存playFirstInQueue函数引用，避免循环依赖
  const currentPlayingIdRef = useRef<string | null>(null) // 追踪当前播放的话术ID
  const addOneToQueueRef = useRef<(() => Promise<void>) | null>(null) // 保存addOneToQueue函数引用
  const startPlayingRef = useRef<(() => Promise<void>) | null>(null) // 保存startPlaying函数引用
  const stopPlayingRef = useRef<(() => void) | null>(null) // 保存stopPlaying函数引用
  const commentsRef = useRef<typeof comments>([]) // ✅ 追踪最新的评论列表（避免闭包问题）
  const isListeningRef = useRef<typeof isListening>('stopped') // ✅ 追踪最新的监听状态
  const currentSequentialIndexRef = useRef<number>(0) // ✅ 追踪最新的顺序索引（避免异步闭包问题）
  
  // 自动播报定时器
  const timeAnnouncementTimerRef = useRef<NodeJS.Timeout | null>(null)
  const welcomeUserTimerRef = useRef<NodeJS.Timeout | null>(null)
  
  // ✅ 追踪上一次的播报状态，避免组件重新挂载时误触发自动启动
  const prevBroadcastingRef = useRef<boolean | null>(null)
  
  // 用户互动去重记录：记录最近播报过的用户行为和时间戳（key格式：userId_msgType）
  const recentBroadcastUsersRef = useRef<Map<string, number>>(new Map())
  
  // 获取全局播放管理器
  const playbackManager = getPlaybackManager()
  
  // 封装全局状态的setter，简化调用
  // 注意：这些setter直接使用当前的prop值，不支持函数形式的更新
  // 如果需要基于当前值更新，需要显式读取previewQueue/recycleBin等
  const setPreviewQueue = useCallback((queue: PreviewQueueItem[]) => {
    // 🔍 调试：记录队列更新
    const oldLength = previewQueueRef.current.length
    const newLength = queue.length
    if (oldLength > 0 && newLength > 0 && oldLength !== newLength) {
      logger.info(`📝 队列长度变化: ${oldLength} → ${newLength}`)
    }
    // ⚠️ 关键：立即同步更新 ref，确保 ref 和状态始终一致
    previewQueueRef.current = queue
    setGlobalPreviewQueue(queue)
  }, [setGlobalPreviewQueue, logger])
  
  const setRecycleBin = useCallback((bin: RecycleBinItem[]) => {
    setGlobalRecycleBin(bin)
  }, [setGlobalRecycleBin])
  
  const setCurrentSequentialIndex = useCallback((index: number) => {
    setGlobalSequentialIndex(index)
  }, [setGlobalSequentialIndex])
  
  const setCurrentPlayingId = useCallback((id: string | null) => {
    setGlobalPlayingId(id)
  }, [setGlobalPlayingId])

  // 折叠状态
  const [isCollapsed, setIsCollapsed] = useState(false)

  // 获取AI配置
  const aiConfig = useAIChatStore((state): ProviderConfig => state.config)
  const aiApiKeys = useAIChatStore((state): Record<AIProvider, string> => state.apiKeys)
  const customBaseURL = useAIChatStore((state): string => state.customBaseURL)
  const getActiveLiveStreamConfig = useAIChatStore((state) => state.getActiveLiveStreamConfig)
  const activeLiveStreamConfig = getActiveLiveStreamConfig()
  
  // 安全获取配置，提供默认值
  const contentRewriteConfig = config.contentRewrite || {
    enable: false,
    scripts: [],
    playback: {
      mode: 'manual' as const,
      interval: [30, 60] as [number, number],
      randomOrder: false,
    },
  }
  
  const { scripts } = contentRewriteConfig
  
  // 提取enable状态，避免useEffect中的对象引用问题
  const isContentRewriteEnabled = contentRewriteConfig.enable
  
  // 使用全局播放配置
  const globalPlayback = config.playback
  
  // 获取启用的话术
  const enabledScripts = scripts.filter(s => s.enabled)
  
  // 获取播放模式（顺序/随机）- 使用内容改写配置中的设置
  const playMode = contentRewriteConfig.playback?.randomOrder ? 'random' : 'sequential'

  // 添加话术
  const handleAddScript = () => {
    if (!newScript.trim()) {
      toast.error('请输入话术内容')
      return
    }

    const newScriptItem = {
      id: crypto.randomUUID(),
      content: newScript.trim(),
      enabled: true,
    }

    updateConfig({
      contentRewrite: {
        ...contentRewriteConfig,
        scripts: [...scripts, newScriptItem],
      },
    })

    setNewScript('')
    toast.success('话术添加成功')
  }

  // 删除话术
  const handleDeleteScript = (id: string) => {
    updateConfig({
      contentRewrite: {
        ...contentRewriteConfig,
        scripts: scripts.filter(s => s.id !== id),
      },
    })
    toast.success('话术已删除')
  }

  // 切换话术启用状态
  const handleToggleScript = (id: string, enabled: boolean) => {
    updateConfig({
      contentRewrite: {
        ...contentRewriteConfig,
        scripts: scripts.map(s => (s.id === id ? { ...s, enabled } : s)),
      },
    })
  }

  // 开始编辑
  const handleStartEdit = (id: string, content: string) => {
    setEditingId(id)
    setEditingContent(content)
  }

  // 保存编辑
  const handleSaveEdit = () => {
    if (!editingContent.trim()) {
      toast.error('话术内容不能为空')
      return
    }

    updateConfig({
      contentRewrite: {
        ...contentRewriteConfig,
        scripts: scripts.map(s =>
          s.id === editingId ? { ...s, content: editingContent.trim() } : s,
        ),
      },
    })

    setEditingId(null)
    setEditingContent('')
    toast.success('话术已更新')
  }

  // 取消编辑
  const handleCancelEdit = () => {
    setEditingId(null)
    setEditingContent('')
  }

  // AI批量生成话术
  const handleAIGenerate = async () => {
    const apiKey = aiApiKeys[aiConfig.provider]
    if (!apiKey) {
      toast.error('请先在AI助手页面配置 API Key')
      return
    }

    if (!aiGenerateStyle && !aiGenerateExample) {
      toast.error('请输入生成风格或提供示例')
      return
    }

    setIsGenerating(true)

    try {
      // 构建生成提示词
      let systemPrompt = '你是一个专业的直播话术生成助手。'
      if (activeLiveStreamConfig) {
        if (activeLiveStreamConfig.role) {
          systemPrompt += `你的角色定位是：${activeLiveStreamConfig.role}。`
        }
        if (activeLiveStreamConfig.positivePrompt) {
          systemPrompt += `${activeLiveStreamConfig.positivePrompt}`
        }
        if (activeLiveStreamConfig.productParams) {
          systemPrompt += `产品信息：${activeLiveStreamConfig.productParams}`
        }
      }

      let userPrompt = `请生成${aiGenerateCount}条直播话术，每条约${aiGenerateLength}字。\n\n`

      if (aiGenerateExample) {
        userPrompt += `参考示例话术（仿写类似风格和内容）：\n${aiGenerateExample}\n\n`
      }

      if (aiGenerateStyle) {
        userPrompt += `风格要求：${aiGenerateStyle}\n\n`
      }

      userPrompt += `要求：
1. 每条话术独立成段，用"---"分隔
2. 内容要口语化、自然
3. 适合直播场景使用
4. 每条话术长度控制在${aiGenerateLength}字左右
5. 直接输出话术内容，不要有序号、标题等额外内容

请按以下格式输出：
话术1内容
---
话术2内容
---
话术3内容
...`

      const messages = [
        { role: 'system', content: systemPrompt },
        { role: 'user', content: userPrompt },
      ]

      const response = await window.ipcRenderer.invoke(
        IPC_CHANNELS.tasks.aiChat.normalChat,
        {
          messages,
          provider: aiConfig.provider,
          model: aiConfig.model,
          apiKey,
          customBaseURL,
        },
      )

      if (!response) {
        throw new Error('AI返回内容为空')
      }

      // 解析生成的话术
      const generatedScripts = response
        .split('---')
        .map((s: string) => s.trim())
        .filter((s: string) => s.length > 0)
        .slice(0, aiGenerateCount)

      if (generatedScripts.length === 0) {
        throw new Error('未能解析出有效话术')
      }

      // 批量添加到话术列表
      const newScripts = generatedScripts.map((content: string) => ({
        id: crypto.randomUUID(),
        content,
        enabled: true,
      }))

      updateConfig({
        contentRewrite: {
          ...contentRewriteConfig,
          scripts: [...scripts, ...newScripts],
        },
      })

      toast.success(`成功生成 ${newScripts.length} 条话术`)
      
      // 重置表单
      setAiGenerateStyle('')
      setAiGenerateExample('')
      setShowAIGenerator(false)
    } catch (err) {
      console.error('AI生成失败:', err)
      toast.error(err instanceof Error ? err.message : 'AI生成失败，请重试')
    } finally {
      setIsGenerating(false)
    }
  }

  // 组件挂载时从全局状态恢复播放状态
  useEffect(() => {
    setIsPlaying(contentRewrite.isPlaying)
    isPlayingRef.current = contentRewrite.isPlaying
  }, [])
  
  // 监听自动播报事件（用户互动、AI回复），将内容加入队列
  useEffect(() => {
    const unsubscribe = window.ipcRenderer.on(
      'ai-assist:add-to-queue' as any,
      (data: any) => {
        // 只处理当前账号的事件
        if (data.accountId !== currentAccountId) return
        
        // 创建队列项
        const queueItem: PreviewQueueItem = {
          id: crypto.randomUUID(),
          type: data.type,
          originalContent: data.originalContent,
          rewrittenContent: data.rewrittenContent,
          timestamp: Date.now(),
        }
        
        // 根据播放模式插入队列
        const currentQueue = previewQueueRef.current
        let newQueue: PreviewQueueItem[]
        
        if (data.playMode === 'immediate') {
          // 立即模式：插入队首
          newQueue = [queueItem, ...currentQueue]
        } else {
          // 等待模式：插入第二位
          if (currentQueue.length === 0) {
            newQueue = [queueItem]
          } else {
            newQueue = [currentQueue[0], queueItem, ...currentQueue.slice(1)]
          }
        }
        
        setPreviewQueue(newQueue)
        
        // 如果当前没有播放且队列中只有这一条，立即触发播放
        if (!currentPlayingIdRef.current && currentQueue.length === 0 && isPlayingRef.current) {
          const manager = getPlaybackManager()
          if (!manager.playTimeout && playFirstInQueueRef.current) {
            playFirstInQueueRef.current()
          }
        }
      }
    )
    
    return () => unsubscribe()
  }, [currentAccountId, setPreviewQueue])

  // ✅ 监听评论列表清空事件，同时清空防重复缓存
  useEffect(() => {
    const handleClearComments = () => {
      recentBroadcastUsersRef.current.clear()
      logger.info('🗑️ [用户互动播报] 已清空防重复缓存')
    }

    // 监听自定义清空事件
    window.addEventListener('clear-comments' as any, handleClearComments)

    return () => {
      window.removeEventListener('clear-comments' as any, handleClearComments)
    }
  }, [logger])

  // 组件卸载时清理定时器
  useEffect(() => {
    return () => {
      if (timeAnnouncementTimerRef.current) {
        clearTimeout(timeAnnouncementTimerRef.current)
        timeAnnouncementTimerRef.current = null
      }
      if (welcomeUserTimerRef.current) {
        clearTimeout(welcomeUserTimerRef.current)
        welcomeUserTimerRef.current = null
      }
    }
  }, [])
  
  // 注意：不在组件卸载时清理定时器，这样切换页面也能继续播放
  // 定时器只在用户主动点击暂停时清理

  // 同步播放状态到ref
  useEffect(() => {
    isPlayingRef.current = isPlaying
  }, [isPlaying])

  // 注意：previewQueueRef 现在在 setPreviewQueue 中立即同步更新，不需要 useEffect
  // useEffect(() => {
  //   previewQueueRef.current = previewQueue
  // }, [previewQueue])

  // 同步回收站状态到ref
  useEffect(() => {
    recycleBinRef.current = recycleBin
  }, [recycleBin])

  // 同步当前播放ID到ref
  useEffect(() => {
    currentPlayingIdRef.current = currentPlayingId
  }, [currentPlayingId])

  // ✅ 同步顺序索引到ref（避免异步闭包问题）
  useEffect(() => {
    currentSequentialIndexRef.current = currentSequentialIndex
  }, [currentSequentialIndex])

  // ✅ 同步评论列表和监听状态到ref（避免定时器闭包问题）
  useEffect(() => {
    commentsRef.current = comments
  }, [comments])

  useEffect(() => {
    isListeningRef.current = isListening
    
    // ✅ 当评论监听停止时，清除用户互动播报定时器
    if (isListening !== 'listening' && welcomeUserTimerRef.current) {
      clearTimeout(welcomeUserTimerRef.current)
      welcomeUserTimerRef.current = null
      logger.info('⏹️ [用户互动播报] 评论监听已停止，清除定时检查')
    }
  }, [isListening, logger])

  // 直接播放（不经过AI改写）- 用于话术列表测试
  const playDirectly = useCallback(
    async (text: string, scriptId?: string) => {
      // 根据厂商检查配置
      const provider = config.provider || 'aliyun'
      if (provider === 'aliyun') {
        if (!config.aliyun.accessKeyId || !config.aliyun.accessKeySecret || !config.aliyun.appKey) {
          toast.error('请先配置阿里云 API')
          return
        }
      } else if (provider === 'tencent') {
        if (!config.tencent?.secretId || !config.tencent?.secretKey) {
          toast.error('请先配置腾讯云 API')
          return
        }
      }

      try {
        // 设置播放状态
        if (scriptId) {
          setTestPlayingScriptId(scriptId)
        }

        // 直接TTS播放
        await window.ipcRenderer.invoke(
          IPC_CHANNELS.tasks.aiAssist.synthesizeVoice,
          {
            text: text,
            voiceConfig: config,
          },
        )
      } catch (err) {
        console.error('播放失败:', err)
        toast.error(err instanceof Error ? err.message : '播放失败，请检查配置')
      } finally {
        // 清除播放状态
        if (scriptId) {
          setTestPlayingScriptId(null)
        }
      }
    },
    [config, toast],
  )

  // AI改写文本
  const rewriteText = useCallback(
    async (originalText: string): Promise<string> => {
      const apiKey = aiApiKeys[aiConfig.provider]
      if (!apiKey) {
        throw new Error('请先在AI助手页面配置 API Key')
      }

      // 构建改写提示词
      let systemPrompt = '你是一个专业的文案改写助手，擅长保持原文字数进行精准改写。'
      if (activeLiveStreamConfig) {
        if (activeLiveStreamConfig.role) {
          systemPrompt += `你的角色定位是：${activeLiveStreamConfig.role}。`
        }
        if (activeLiveStreamConfig.positivePrompt) {
          systemPrompt += `${activeLiveStreamConfig.positivePrompt}`
        }
        if (activeLiveStreamConfig.negativePrompt) {
          systemPrompt += `注意避免：${activeLiveStreamConfig.negativePrompt}`
        }
        if (activeLiveStreamConfig.productParams) {
          systemPrompt += `产品信息：${activeLiveStreamConfig.productParams}`
        }
      }

      const originalLength = originalText.length
      const minLength = Math.max(1, originalLength - 10)
      const maxLength = originalLength + 10
      
      const userPrompt = `请将以下直播话术进行改写，保持原意但用不同的表达方式。

原话术：${originalText}

要求：
1. 保持核心意思完全不变
2. 可以调整语序、替换同义词
3. 语气要自然、口语化
4. 字数控制在 ${minLength} 到 ${maxLength} 字之间
5. 直接输出改写后的文本，不要有任何解释说明`

      const messages = [
        { role: 'system', content: systemPrompt },
        { role: 'user', content: userPrompt },
      ]

      try {
        const rewrittenText = await window.ipcRenderer.invoke(
          IPC_CHANNELS.tasks.aiChat.normalChat,
          {
            messages,
            provider: aiConfig.provider,
            model: aiConfig.model,
            apiKey,
            customBaseURL,
          },
        )

        const result = rewrittenText || originalText
        logger.success(`AI改写完成: ${result.substring(0, 20)}...`)
        return result
      } catch (err) {
        logger.error(`AI改写失败: ${err instanceof Error ? err.message : String(err)}`)
        throw err
      }
    },
    [aiConfig, aiApiKeys, customBaseURL, activeLiveStreamConfig, logger],
  )

  // 生成单个预览队列项
  const generatePreviewItem = useCallback(
    async (originalContent: string): Promise<PreviewQueueItem> => {
      const rewrittenText = await rewriteText(originalContent)
      return {
        id: crypto.randomUUID(),
        type: 'live_script' as const, // ✅ 修复类型：添加 type 字段
        originalContent,
        rewrittenContent: rewrittenText,
        timestamp: Date.now(),
      }
    },
    [rewriteText],
  )

  // 初始化/刷新队列（生成5条）
  const initializeQueue = useCallback(async () => {
    if (enabledScripts.length === 0) {
      toast.error('请先添加并启用话术')
      return
    }

    // ⚠️ 防止在播放期间替换队列
    if (isPlayingRef.current && previewQueueRef.current.length > 0) {
      logger.warn('⚠️ 播放期间不允许替换队列！')
      return
    }

    setIsLoadingQueue(true)
    logger.info('🚀 开始并行初始化预览队列（5条话术）...')

    try {
      // 🚀 优化：并行生成所有话术，而不是串行等待
      const scriptsToGenerate = []
      
      // ✅ 使用 ref 获取最新的索引值
      const startIndex = currentSequentialIndexRef.current
      
      for (let i = 0; i < 5; i++) {
        let script
        
        if (playMode === 'random') {
          // 随机模式
          const randomIndex = Math.floor(Math.random() * enabledScripts.length)
          script = enabledScripts[randomIndex]
        } else {
          // 顺序模式 - 使用 startIndex
          const index = (startIndex + i) % enabledScripts.length
          script = enabledScripts[index]
        }
        
        scriptsToGenerate.push(script.content)
      }
      
      // 并行生成所有预览项
      const promises = scriptsToGenerate.map(content => 
        generatePreviewItem(content).catch(err => {
          logger.error(`生成预览项失败: ${err instanceof Error ? err.message : String(err)}`)
          return null
        })
      )
      
      const results = await Promise.all(promises)
      const items = results.filter((item): item is PreviewQueueItem => item !== null)

      if (playMode === 'sequential') {
        const newIndex = (startIndex + 5) % enabledScripts.length
        setCurrentSequentialIndex(newIndex)
        currentSequentialIndexRef.current = newIndex // ✅ 同步更新 ref
      }

      setPreviewQueue(items)
      logger.success(`✅ 队列初始化完成，共 ${items.length} 条（并行生成，速度更快）`)
      toast.success(`队列已生成 ${items.length} 条话术`)
    } catch (err) {
      logger.error(`队列初始化失败: ${err instanceof Error ? err.message : String(err)}`)
      toast.error('队列初始化失败')
    } finally {
      setIsLoadingQueue(false)
    }
  }, [enabledScripts, playMode, generatePreviewItem, logger, toast, setPreviewQueue, setCurrentSequentialIndex])

  // 补充一条新话术到队列末尾
  const addOneToQueue = useCallback(async () => {
    if (enabledScripts.length === 0) return

    try {
      let script
      let selectedIndex: number
      
      // ✅ 使用 ref 获取最新的索引值
      const currentIndex = currentSequentialIndexRef.current
      
      if (playMode === 'random') {
        selectedIndex = Math.floor(Math.random() * enabledScripts.length)
        script = enabledScripts[selectedIndex]
      } else {
        selectedIndex = currentIndex % enabledScripts.length
        script = enabledScripts[selectedIndex]
        const newIndex = (currentIndex + 1) % enabledScripts.length
        setCurrentSequentialIndex(newIndex)
        currentSequentialIndexRef.current = newIndex // ✅ 同步更新 ref
      }
      
      const item = await generatePreviewItem(script.content)
      
      // 🔒 添加到队列末尾，确保不影响其他类型（报时、互动等）的播放顺序
      const currentQueueSnapshot = [...previewQueueRef.current]
      const newQueue = [...currentQueueSnapshot, item]
      setPreviewQueue(newQueue)
      
      logger.info(`📥 队列补充完成: 添加话术到末尾 (索引: ${selectedIndex})。队列长度: ${currentQueueSnapshot.length} → ${newQueue.length}`)
    } catch (err) {
      logger.error(`补充队列失败: ${err instanceof Error ? err.message : String(err)}`)
    }
  }, [enabledScripts, playMode, generatePreviewItem, logger, setPreviewQueue, setCurrentSequentialIndex])

  // 批量补充话术到队列（保持5条话术）
  const addMultipleToQueue = useCallback(async (count: number) => {
    if (enabledScripts.length === 0 || count <= 0) return

    try {
      // 🚀 优化：并行生成所有话术，而不是串行等待
      const scriptsToGenerate = []
      
      // ✅ 使用 ref 获取最新的索引值
      const startIndex = currentSequentialIndexRef.current
      
      for (let i = 0; i < count; i++) {
        let script
        
        if (playMode === 'random') {
          const randomIndex = Math.floor(Math.random() * enabledScripts.length)
          script = enabledScripts[randomIndex]
        } else {
          const index = (startIndex + i) % enabledScripts.length
          script = enabledScripts[index]
        }
        
        scriptsToGenerate.push(script.content)
      }
      
      // 并行生成所有预览项
      const promises = scriptsToGenerate.map(content => 
        generatePreviewItem(content).catch(err => {
          logger.error(`生成话术失败: ${err instanceof Error ? err.message : String(err)}`)
          return null
        })
      )
      
      const results = await Promise.all(promises)
      const items = results.filter((item): item is PreviewQueueItem => item !== null)
      
      if (items.length > 0) {
        // 更新顺序索引
        if (playMode === 'sequential') {
          const newIndex = (startIndex + items.length) % enabledScripts.length
          setCurrentSequentialIndex(newIndex)
          currentSequentialIndexRef.current = newIndex // ✅ 同步更新 ref
        }
        
        // 添加到队列末尾
        const currentQueueSnapshot = [...previewQueueRef.current]
        const newQueue = [...currentQueueSnapshot, ...items]
        setPreviewQueue(newQueue)
        
        logger.info(`📥 批量补充完成: 并行添加 ${items.length} 条话术到末尾 (起始索引: ${startIndex})。队列长度: ${currentQueueSnapshot.length} → ${newQueue.length}`)
      }
    } catch (err) {
      logger.error(`批量补充队列失败: ${err instanceof Error ? err.message : String(err)}`)
    }
  }, [enabledScripts, playMode, generatePreviewItem, logger, setPreviewQueue, setCurrentSequentialIndex])

  // 同步addOneToQueue函数到ref
  useEffect(() => {
    addOneToQueueRef.current = addOneToQueue
  }, [addOneToQueue])

  // 生成报时文本
  const generateTimeAnnouncement = useCallback(() => {
    const now = new Date()
    const hours = now.getHours()
    const minutes = now.getMinutes()
    const timeStr = `${hours}:${minutes.toString().padStart(2, '0')}`
    
    // 过滤空行和空字符串
    const allTemplates = globalPlayback?.timeAnnouncement?.templates || ['当前时间{时间}']
    const templates = allTemplates.filter(t => t && t.trim())
    
    // 如果过滤后没有模板，使用默认模板
    const validTemplates = templates.length > 0 ? templates : ['当前时间{时间}']
    const mode = globalPlayback?.timeAnnouncement?.mode || 'random'
    
    let selectedTemplate: string
    
    if (mode === 'random') {
      selectedTemplate = validTemplates[Math.floor(Math.random() * validTemplates.length)]
    } else {
      const index = templateSequentialIndex.time % validTemplates.length
      selectedTemplate = validTemplates[index]
      setTemplateSequentialIndex(prev => ({ ...prev, time: prev.time + 1 }))
    }
    
    return selectedTemplate.replace('{时间}', timeStr)
  }, [globalPlayback, templateSequentialIndex.time])

  // 生成用户互动播报文本
  const generateInteractionMessage = useCallback((
    type: EventMessageType, 
    username: string = '新朋友',
    productName?: string
  ) => {
    // 优先使用新的userInteraction配置，兼容旧的welcomeUser配置
    const userInteractionConfig = globalPlayback?.userInteraction
    const welcomeUserConfig = globalPlayback?.welcomeUser
    
    // 默认模板
    const defaultTemplates: Record<EventMessageType, string[]> = {
      room_enter: ['欢迎{用户}来到直播间', '欢迎{用户}的到来', '{用户}来啦，大家欢迎'],
      room_like: ['感谢{用户}的点赞', '谢谢{用户}点赞支持', '{用户}点赞了，谢谢支持'],
      room_follow: ['感谢{用户}的关注', '欢迎{用户}关注直播间', '谢谢{用户}关注'],
      subscribe_merchant_brand_vip: ['欢迎{用户}加入品牌会员', '感谢{用户}成为品牌会员', '{用户}加入了品牌会员，感谢支持'],
      live_order: ['感谢{用户}购买{商品}', '谢谢{用户}的订单', '{用户}购买了{商品}，感谢支持'],
      ecom_fansclub_participate: ['欢迎{用户}加入粉丝团', '感谢{用户}加入粉丝团', '{用户}加入粉丝团啦，谢谢支持'],
    }
    
    let templates: string[]
    let mode: 'random' | 'sequential' = 'random'
    
    if (userInteractionConfig?.enable) {
      // 使用新的userInteraction配置，过滤空行和空字符串
      templates = (userInteractionConfig.templates[type] || defaultTemplates[type]).filter(t => t && t.trim())
      mode = userInteractionConfig.mode || 'random'
    } else if (welcomeUserConfig?.enable && type === 'room_enter') {
      // 兼容旧的welcomeUser配置（只对进入直播间有效），过滤空行和空字符串
      templates = (welcomeUserConfig.templates || defaultTemplates[type]).filter(t => t && t.trim())
      mode = welcomeUserConfig.mode || 'random'
    } else {
      templates = defaultTemplates[type]
    }
    
    // 确保templates不为空
    if (!templates || templates.length === 0) {
      templates = defaultTemplates[type]
    }
    
    let selectedTemplate: string
    
    if (mode === 'random') {
      selectedTemplate = templates[Math.floor(Math.random() * templates.length)]
    } else {
      const index = templateSequentialIndex.welcome % templates.length
      selectedTemplate = templates[index]
      setTemplateSequentialIndex(prev => ({ ...prev, welcome: prev.welcome + 1 }))
    }
    
    // 替换占位符
    let result = selectedTemplate.replace(/{用户}/g, username)
    if (productName) {
      result = result.replace(/{商品}/g, productName)
    }
    
    return result
  }, [globalPlayback, templateSequentialIndex.welcome])

  // 一键播报报时 - 添加到队列
  const handleQuickTimeAnnouncement = useCallback((isAuto = false) => {
    // 🛡️ 防止重复添加：如果队列中已有报时，则跳过（自动报时时）
    const currentQueue = previewQueueRef.current
    if (isAuto) {
      const hasTimeAnnouncement = currentQueue.some(item => item.type === 'time_announcement')
      if (hasTimeAnnouncement) {
        logger.info('⏰ 队列中已有报时，跳过本次自动报时')
        return
      }
    }
    
    const timeText = generateTimeAnnouncement()
    logger.info(`⏰ 添加报时到队列: ${timeText}`)
    
    // 创建报时队列项
    const timeItem: PreviewQueueItem = {
      id: crypto.randomUUID(),
      type: 'time_announcement',
      originalContent: timeText,
      rewrittenContent: timeText, // 报时不需要AI改写
      timestamp: Date.now(),
    }
    
    // 根据播放模式插入队列
    let newQueue: PreviewQueueItem[]
    
    if (quickPlayMode === 'immediate') {
      // 立即模式：插入队首
      newQueue = [timeItem, ...currentQueue]
      if (!isAuto) toast.success('报时已加入队列（优先播放）')
      logger.info('⏰ [报时播报] 已插入队首（立即播放）')
    } else {
      // 等待模式：插入第二位
      if (currentQueue.length === 0) {
        newQueue = [timeItem]
      } else {
        newQueue = [currentQueue[0], timeItem, ...currentQueue.slice(1)]
      }
      if (!isAuto) toast.success('报时已加入队列')
      logger.info('⏰ [报时播报] 已插入队列第二位（等待播放）')
    }
    
    setPreviewQueue(newQueue)
    
    // 如果是立即模式且正在播放，停止当前音频
    if (quickPlayMode === 'immediate' && isPlayingRef.current && currentPlayingIdRef.current) {
      logger.info('⏸️ 立即播放模式：停止当前音频，准备播放报时')
      ;(window.ipcRenderer as any).send('tts:stop-audio')
    } else if (!currentPlayingIdRef.current && currentQueue.length === 0 && isPlayingRef.current) {
      // 如果当前没有播放且队列中只有这一条，立即触发播放
      const manager = getPlaybackManager()
      if (!manager.playTimeout && playFirstInQueueRef.current) {
        playFirstInQueueRef.current()
      }
    }
  }, [generateTimeAnnouncement, quickPlayMode, setPreviewQueue, toast, logger])

  // 一键播报用户互动 - 添加到队列
  const handleQuickUserInteraction = useCallback((isAuto = false) => {
    // ✅ 修复：始终使用 ref 获取最新值（避免定时器闭包问题，同时避免函数频繁重建）
    const currentComments = commentsRef.current
    const currentListening = isListeningRef.current
    
    // 检查评论监听是否启动
    if (currentListening !== 'listening') {
      if (!isAuto) {
        toast.error('请先启动评论列表监听')
      } else {
        logger.info(`⚠️ [用户互动播报] 评论监听未启动(状态: ${currentListening})，跳过`)
      }
      return
    }
    
    // 🔍 调试：打印所有评论
    logger.info(`🔍 [调试${isAuto ? '-自动' : '-手动'}] 当前评论总数: ${currentComments.length}`)
    if (currentComments.length > 0) {
      const msgTypes = currentComments.map(msg => msg.msg_type)
      logger.info(`🔍 [调试] 所有评论类型: ${msgTypes.join(', ')}`)
      // 打印前3条评论的详细信息
      currentComments.slice(0, 3).forEach((msg, idx) => {
        logger.info(`🔍 [调试] 评论${idx + 1}: ${msg.nick_name} - ${msg.msg_type}`)
      })
    }
    
    // 筛选出非评论类型的互动消息
    let interactionMessages = currentComments.filter(msg => msg.msg_type !== 'comment')
    
    logger.info(`🔍 [调试] 筛选后的互动消息数量: ${interactionMessages.length}`)
    
    if (interactionMessages.length === 0) {
      if (!isAuto) {
        toast.error('暂无用户互动消息')
      } else {
        logger.info('⚠️ [用户互动播报] 暂无用户互动消息，跳过')
      }
      return
    }
    
    logger.info(`🔍 [用户互动播报] 检测到 ${interactionMessages.length} 条互动消息，类型: ${[...new Set(interactionMessages.map(m => m.msg_type))].join(', ')}`)
    
    // 防重复检查
    const deduplicationConfig = globalPlayback?.userInteraction?.deduplication
    const now = Date.now()
    
    if (deduplicationConfig?.enable && deduplicationConfig.duration > 0) {
      const durationMs = deduplicationConfig.duration * 1000
      const recentUserActions = recentBroadcastUsersRef.current
      
      // 清理过期记录
      for (const [actionKey, timestamp] of recentUserActions.entries()) {
        if (now - timestamp > durationMs) {
          recentUserActions.delete(actionKey)
        }
      }
      
      // 过滤已播报的
      interactionMessages = interactionMessages.filter(msg => {
        const userId = 'user_id' in msg ? msg.user_id : msg.msg_id
        const actionKey = `${userId}_${msg.msg_type}`
        const lastBroadcast = recentUserActions.get(actionKey)
        return !(lastBroadcast && (now - lastBroadcast <= durationMs))
      })
      
      if (interactionMessages.length === 0) {
        logger.info('⚠️ [用户互动播报] 所有互动消息已在防重复时间窗口内播报过，跳过')
        return
      }
      
      logger.info(`✅ [用户互动播报] 防重复过滤后剩余 ${interactionMessages.length} 条消息`)
    }
    
    // 随机选择一条互动消息
    const randomMsg = interactionMessages[Math.floor(Math.random() * interactionMessages.length)]
    const username = randomMsg.nick_name || '新朋友'
    const msgType = randomMsg.msg_type as EventMessageType
    const userId = 'user_id' in randomMsg ? randomMsg.user_id : randomMsg.msg_id
    
    // 获取商品名称（如果是购买商品类型）
    let productName: string | undefined
    if (msgType === 'live_order' && 'product_title' in randomMsg) {
      productName = randomMsg.product_title
    }
    
    // 生成互动播报文本
    const interactionText = generateInteractionMessage(msgType, username, productName)
    
    // ✅ 修复：自动播报使用全局配置的 playMode，手动一键播报使用 quickPlayMode
    const playModeToUse = isAuto 
      ? (globalPlayback?.userInteraction?.playMode || 'next')  // 自动：使用全局配置
      : quickPlayMode  // 手动：使用一键播报UI配置
    
    logger.info(`📢 [用户互动播报] ${isAuto ? '自动检测' : '手动触发'} - ${username} ${msgType} - 播放模式: ${playModeToUse}`)
    
    // 创建用户互动队列项（区分自动和手动）
    const interactionItem: PreviewQueueItem = {
      id: crypto.randomUUID(),
      type: isAuto ? 'user_interaction' : 'quick_broadcast', // 自动用user_interaction，手动用quick_broadcast
      originalContent: `${username} - ${msgType}`,
      rewrittenContent: interactionText,
      timestamp: Date.now(),
    }
    
    // 记录已播报的用户行为（如果启用了防重复）
    if (deduplicationConfig?.enable && deduplicationConfig.duration > 0) {
      const actionKey = `${userId}_${msgType}`
      recentBroadcastUsersRef.current.set(actionKey, now)
    }
    
    // 根据播放模式插入队列
    const currentQueue = previewQueueRef.current
    let newQueue: PreviewQueueItem[]
    
    if (playModeToUse === 'immediate') {
      // 立即模式：插入队首
      newQueue = [interactionItem, ...currentQueue]
      if (!isAuto) toast.success('用户互动已加入队列（优先播放）')
      logger.info(`💬 [用户互动播报] 已插入队首（立即播放）: ${interactionText.substring(0, 30)}...`)
    } else {
      // 等待模式：插入第二位
      if (currentQueue.length === 0) {
        newQueue = [interactionItem]
      } else {
        newQueue = [currentQueue[0], interactionItem, ...currentQueue.slice(1)]
      }
      if (!isAuto) toast.success('用户互动已加入队列')
      logger.info(`💬 [用户互动播报] 已插入队列第二位（等待播放）: ${interactionText.substring(0, 30)}...`)
    }
    
    setPreviewQueue(newQueue)
    
    // 如果是立即模式且正在播放，停止当前音频
    if (playModeToUse === 'immediate' && isPlayingRef.current && currentPlayingIdRef.current) {
      logger.info('⏸️ 立即播放模式：停止当前音频，准备播放用户互动')
      ;(window.ipcRenderer as any).send('tts:stop-audio')
    } else if (!currentPlayingIdRef.current && currentQueue.length === 0 && isPlayingRef.current) {
      // 如果当前没有播放且队列中只有这一条，立即触发播放
      const manager = getPlaybackManager()
      if (!manager.playTimeout && playFirstInQueueRef.current) {
        playFirstInQueueRef.current()
      }
    }
  }, [generateInteractionMessage, quickPlayMode, setPreviewQueue, toast, globalPlayback, logger])

  // 调度下一次自动报时
  const scheduleNextTimeAnnouncement = useCallback(() => {
    // 清除之前的定时器
    if (timeAnnouncementTimerRef.current) {
      clearTimeout(timeAnnouncementTimerRef.current)
      timeAnnouncementTimerRef.current = null
    }

    // 检查是否启用
    if (!globalPlayback?.timeAnnouncement?.enable) {
      return
    }

    // 计算下次触发时间（分钟转毫秒）
    const min = (globalPlayback.timeAnnouncement.interval?.min || 5) * 60 * 1000
    const max = (globalPlayback.timeAnnouncement.interval?.max || 10) * 60 * 1000
    const delay = Math.random() * (max - min) + min

    timeAnnouncementTimerRef.current = setTimeout(() => {
      if (contentRewriteConfig.enable && isPlayingRef.current) {
        handleQuickTimeAnnouncement(true)
        scheduleNextTimeAnnouncement() // 继续调度下一次
      }
    }, delay)
  }, [globalPlayback, contentRewriteConfig.enable, handleQuickTimeAnnouncement, logger])

  // 调度下一次自动用户互动播报
  const scheduleNextUserInteraction = useCallback(() => {
    // 清除之前的定时器
    if (welcomeUserTimerRef.current) {
      clearTimeout(welcomeUserTimerRef.current)
      welcomeUserTimerRef.current = null
    }

    // 检查是否启用（优先使用新的userInteraction配置，兼容旧的welcomeUser）
    const userInteractionConfig = globalPlayback?.userInteraction
    const welcomeUserConfig = globalPlayback?.welcomeUser
    
    const isEnabled = userInteractionConfig?.enable || welcomeUserConfig?.enable
    if (!isEnabled) {
      return // 未启用，静默返回
    }

    // ✅ 检查评论监听状态 - 用户互动播报依赖评论数据
    const currentListening = isListeningRef.current
    if (currentListening !== 'listening') {
      logger.info('⏹️ [用户互动播报] 评论监听未启动，停止定时检查')
      return
    }

    // 计算下次触发时间（秒转毫秒）
    const interval = userInteractionConfig?.interval || welcomeUserConfig?.interval
    // 新配置使用秒，旧配置使用分钟，需要做兼容处理
    let min: number
    let max: number
    
    if (userInteractionConfig?.interval) {
      // 新配置：秒
      min = (interval?.min || 30) * 1000
      max = (interval?.max || 60) * 1000
    } else {
      // 旧配置兼容：分钟转秒
      min = (interval?.min || 3) * 60 * 1000
      max = (interval?.max || 5) * 60 * 1000
    }
    
    const delay = Math.random() * (max - min) + min
    const delaySeconds = (delay / 1000).toFixed(1)

    logger.info(`⏰ [用户互动播报] 已设置定时检查，下次触发: ${delaySeconds}秒后`)

    welcomeUserTimerRef.current = setTimeout(() => {
      if (contentRewriteConfig.enable && isPlayingRef.current) {
        logger.info('⏰ [用户互动播报] 定时检查触发')
        handleQuickUserInteraction(true)
        scheduleNextUserInteraction() // 继续调度下一次
      } else {
        logger.info('⏹️ [用户互动播报] 定时检查跳过（播放已停止或功能未启用）')
      }
    }, delay)
  }, [globalPlayback, contentRewriteConfig.enable, handleQuickUserInteraction, logger])

  // ✅ 监听评论监听状态变化，启动时重新调度用户互动播报定时器
  useEffect(() => {
    if (isListening === 'listening' && isPlayingRef.current) {
      // 当评论监听启动且播放任务正在运行时，重新启动用户互动播报定时器
      logger.info('✅ [用户互动播报] 评论监听已启动，开始定时检查')
      scheduleNextUserInteraction()
    }
  }, [isListening, logger, scheduleNextUserInteraction])

  // 播放队列中的第一条
  const playFirstInQueue = useCallback(async () => {
    // ⚠️ 关键：每次都从 ref 读取最新队列，不要锁定（避免闭包问题）
    const currentQueue = previewQueueRef.current
    
    if (currentQueue.length === 0) {
      setIsPlaying(false)
      isPlayingRef.current = false
      setContentRewritePlaying(false)
      setCurrentPlayingId(null)
      return
    }

    // 🔒 锁定要播放的项（注意：锁定的是项，不是队列）
    const itemToPlay = { ...currentQueue[0] }
    const typeName = itemToPlay.type === 'live_script' ? '话术' : 
                     itemToPlay.type === 'time_announcement' ? '报时' :
                     itemToPlay.type === 'quick_broadcast' ? '互动' :
                     itemToPlay.type === 'user_interaction' ? '互动' : 'AI回复'

    logger.info(`🎵 准备播放 [${typeName}]: ${itemToPlay.rewrittenContent.substring(0, 30)}... (队列长度: ${currentQueue.length}, 项ID: ${itemToPlay.id.slice(0,8)})`)

    try {
      // 设置当前播放ID
      setCurrentPlayingId(itemToPlay.id)
      logger.info(`🔊 开始语音合成 [${typeName}] ID: ${itemToPlay.id}`)

      // 播放音频
      await window.ipcRenderer.invoke(
        IPC_CHANNELS.tasks.aiAssist.synthesizeVoice,
        {
          text: itemToPlay.rewrittenContent,
          voiceConfig: config,
        },
      )

      logger.info(`🎤 语音播放完成 [${typeName}] ID: ${itemToPlay.id}`)
      
      // 清除当前播放ID
      setCurrentPlayingId(null)

      // 只有话术类型才移入回收站
      if (itemToPlay.type === 'live_script') {
        const newRecycleBin = [{
          id: itemToPlay.id,
          type: 'live_script' as const,
          originalContent: itemToPlay.originalContent,
          rewrittenContent: itemToPlay.rewrittenContent,
          playedAt: Date.now(),
        }, ...recycleBinRef.current]
        setRecycleBin(newRecycleBin)
      }

      // 🗑️ 从队列移除已播放的项
      // ⚠️ 关键：必须从全局 ref 中精确移除，因为异步补充队列可能已修改了队列
      const globalQueue = [...previewQueueRef.current]
      
      logger.info(`📋 当前队列状态 (移除前): [${globalQueue.map((item, idx) => `${idx}: ${item.type}(${item.id.slice(0,8)})`).join(', ')}]`)
      
      const playedItemIndex = globalQueue.findIndex(item => item.id === itemToPlay.id)
      
      if (playedItemIndex === -1) {
        logger.error(`❌ 错误：在队列中找不到已播放的项 [${typeName}] ID: ${itemToPlay.id}`)
      } else if (playedItemIndex !== 0) {
        logger.warn(`⚠️ 警告：播放的项不在队列首位，位置: ${playedItemIndex}。这可能是异步补充队列导致的！`)
      }
      
      // 移除已播放的项
      const finalQueue = globalQueue.filter(item => item.id !== itemToPlay.id)
      
      // 注意：setPreviewQueue 已经会同步更新 ref 了
      setPreviewQueue(finalQueue)
      
      logger.info(`✅ ${typeName}播放完成，已从队列移除。剩余队列: ${finalQueue.length} 项`)
      logger.info(`📋 队列状态 (移除后): [${finalQueue.map((item, idx) => `${idx}: ${item.type}(${item.id.slice(0,8)})`).join(', ')}]`)

      // 🚀 在播放完成后补充队列（只补充话术类型）
      if (itemToPlay.type === 'live_script' && isPlayingRef.current) {
        // 统计当前队列中的话术数量
        const scriptCount = finalQueue.filter(item => item.type === 'live_script').length
        const TARGET_SCRIPT_COUNT = 5 // 目标保持5条话术
        
        if (scriptCount < TARGET_SCRIPT_COUNT) {
          const needToAdd = TARGET_SCRIPT_COUNT - scriptCount
          logger.info(`📥 队列话术不足(当前${scriptCount}条)，需要补充${needToAdd}条到${TARGET_SCRIPT_COUNT}条`)
          
          // 使用批量补充函数
          addMultipleToQueue(needToAdd).catch(err => {
            logger.error(`批量补充队列失败: ${err instanceof Error ? err.message : String(err)}`)
          })
        } else {
          logger.info(`✅ 队列话术充足(当前${scriptCount}条)，无需补充`)
        }
      }

      // 如果还在播放状态，继续播放下一条
      if (isPlayingRef.current && finalQueue.length > 0) {
        const nextItem = finalQueue[0]
        
        // 🚨 关键：先清除所有旧的定时器，防止重复触发
        const manager = getPlaybackManager()
        if (manager.countdownTimer) {
          clearInterval(manager.countdownTimer)
          manager.countdownTimer = null
        }
        if (manager.playTimeout) {
          clearTimeout(manager.playTimeout)
          manager.playTimeout = null
        }
        setCountdown(0)
        
        // 只有下一个是话术类型才需要间隔，其他类型立即播放
        if (nextItem.type === 'live_script') {
          const min = globalPlayback?.interval?.min || 3
          const max = globalPlayback?.interval?.max || 10
          const delaySeconds = Math.random() * (max - min) + min

          logger.info(`⏱️ 下一个是话术，等待 ${delaySeconds.toFixed(1)} 秒`)
          
          // 启动倒计时
          let remainingSeconds = Math.ceil(delaySeconds)
          setCountdown(remainingSeconds)
          
          manager.countdownTimer = setInterval(() => {
            remainingSeconds--
            if (remainingSeconds > 0) {
              setCountdown(remainingSeconds)
            } else {
              if (manager.countdownTimer) {
                clearInterval(manager.countdownTimer)
                manager.countdownTimer = null
              }
              setCountdown(0)
            }
          }, 1000)

          manager.playTimeout = setTimeout(() => {
            if (manager.countdownTimer) {
              clearInterval(manager.countdownTimer)
              manager.countdownTimer = null
            }
            setCountdown(0)
            playFirstInQueue()
          }, delaySeconds * 1000)
        } else {
          // 非话术类型，立即播放下一条
          logger.info(`⚡ 下一个是${nextItem.type === 'time_announcement' ? '报时' : '互动'}，立即播放`)
          logger.info(`🔍 验证：当前 ref 队列第一项 = ${previewQueueRef.current[0]?.type}(${previewQueueRef.current[0]?.id.slice(0,8)})`)
          playFirstInQueue()
        }
      }
    } catch (err) {
      logger.error(`播放失败: ${err instanceof Error ? err.message : String(err)}`)
      toast.error('播放失败')
      setIsPlaying(false)
      isPlayingRef.current = false
      setContentRewritePlaying(false)
      setCurrentPlayingId(null)
    }
  }, [config, globalPlayback, logger, toast, setCurrentPlayingId, setContentRewritePlaying, setPreviewQueue, setRecycleBin])

  // 同步playFirstInQueue函数到ref（避免循环依赖）
  useEffect(() => {
    playFirstInQueueRef.current = playFirstInQueue
  }, [playFirstInQueue])

  // 开始播放
  const startPlaying = useCallback(async () => {
    if (isPlayingRef.current) {
      logger.warn('已在播放中')
      return
    }

    // ✅ 检查话术列表
    const enabledScriptsCount = enabledScripts.length
    if (enabledScriptsCount === 0) {
      toast.error('请先添加话术模板！话术列表为空，AI无法进行改写')
      logger.error('❌ 启动失败：话术列表为空')
      return
    }
    
    if (enabledScriptsCount < 5) {
      toast.error(`话术数量不足！当前已启用 ${enabledScriptsCount} 条，建议至少添加 5 条话术以获得更好的效果`)
      logger.error(`❌ 启动失败：话术数量不足（${enabledScriptsCount}/5）`)
      return
    }
    
    logger.info(`✅ 话术检查通过：共有 ${enabledScriptsCount} 条已启用话术`)

    if (previewQueueRef.current.length === 0) {
      toast.success('正在初始化队列...')
      await initializeQueue()
      // 等待队列更新
      await new Promise(resolve => setTimeout(resolve, 500))
    }

    if (previewQueueRef.current.length === 0) {
      toast.error('队列为空，请先添加话术')
      return
    }

    logger.info('开始自动播放')
    setIsPlaying(true)
    isPlayingRef.current = true
    setContentRewritePlaying(true) // 同步到全局状态
    toast.success('开始播放')
    
    // 启动自动播报定时器
    scheduleNextTimeAnnouncement()
    scheduleNextUserInteraction()
    
    playFirstInQueue()
  }, [enabledScripts, initializeQueue, playFirstInQueue, logger, toast, setContentRewritePlaying, scheduleNextTimeAnnouncement, scheduleNextUserInteraction])

  // 停止播放
  const stopPlaying = useCallback(() => {
    setIsPlaying(false)
    isPlayingRef.current = false
    setContentRewritePlaying(false)
    setCurrentPlayingId(null)
    
    // 清除全局定时器和锁
    const manager = getPlaybackManager()
    if (manager.countdownTimer) {
      clearInterval(manager.countdownTimer)
      manager.countdownTimer = null
    }
    if (manager.playTimeout) {
      clearTimeout(manager.playTimeout)
      manager.playTimeout = null
    }
    if (manager.isAIReplying) {
      manager.isAIReplying = false
    }
    
    // 清除自动播报定时器
    if (timeAnnouncementTimerRef.current) {
      clearTimeout(timeAnnouncementTimerRef.current)
      timeAnnouncementTimerRef.current = null
    }
    if (welcomeUserTimerRef.current) {
      clearTimeout(welcomeUserTimerRef.current)
      welcomeUserTimerRef.current = null
    }
    
    setCountdown(0)
    
    // 停止当前正在播放的音频
    window.ipcRenderer.send('tts:stop-audio' as any)
    
    toast.success('已停止播放')
  }, [toast, setCurrentPlayingId, setContentRewritePlaying])

  // 同步startPlaying和stopPlaying函数到ref
  useEffect(() => {
    startPlayingRef.current = startPlaying
  }, [startPlaying])

  useEffect(() => {
    stopPlayingRef.current = stopPlaying
  }, [stopPlaying])

  // ✅ 监听AI助播任务状态变化，自动启动/停止内容改写播放
  useEffect(() => {
    if (!isContentRewriteEnabled) {
      return // 如果未启用内容改写功能，不自动启动
    }

    // ✅ 首次挂载时，只记录当前状态，不执行任何操作
    if (prevBroadcastingRef.current === null) {
      prevBroadcastingRef.current = isBroadcasting
      return
    }

    // ✅ 只有当状态真正发生变化时才执行操作
    if (isBroadcasting !== prevBroadcastingRef.current) {
      if (isBroadcasting && !isPlayingRef.current) {
        // AI助播启动时，自动启动内容改写播放
        logger.info('🎬 AI助播已启动，自动启动内容改写播放')
        if (startPlayingRef.current) {
          startPlayingRef.current()
        }
      } else if (!isBroadcasting && isPlayingRef.current) {
        // AI助播停止时，自动停止内容改写播放
        logger.info('⏹️ AI助播已停止，自动停止内容改写播放')
        if (stopPlayingRef.current) {
          stopPlayingRef.current()
        }
      }
      
      // 更新上一次的状态
      prevBroadcastingRef.current = isBroadcasting
    }
  }, [isBroadcasting, isContentRewriteEnabled, logger])

  return (
    <>
    <Card className="shadow-sm">
      <CardHeader className="pb-3">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-2 flex-1">
            <div>
              <CardTitle>内容改写播放</CardTitle>
              <CardDescription>
                预设直播话术，AI智能改写后播放，模拟真人说话效果
              </CardDescription>
            </div>
          </div>
          <div className="flex items-center gap-3">
            <div className="flex items-center gap-2">
              <Switch
                checked={contentRewriteConfig.enable}
                onCheckedChange={checked =>
                  updateConfig({
                    contentRewrite: { ...contentRewriteConfig, enable: checked },
                  })
                }
              />
              <Label>启用功能</Label>
            </div>
            <Button
              variant="ghost"
              size="sm"
              onClick={() => setIsCollapsed(!isCollapsed)}
              className="h-8 w-8 p-0"
            >
              {isCollapsed ? (
                <ChevronDown className="h-4 w-4" />
              ) : (
                <ChevronUp className="h-4 w-4" />
              )}
            </Button>
          </div>
        </div>
      </CardHeader>
      <Collapsible open={!isCollapsed}>
        <CollapsibleContent>
          <CardContent className="space-y-4">
        {!contentRewriteConfig.enable ? (
          <div className="text-center py-8 text-muted-foreground">
            请启用功能后使用
          </div>
        ) : (
          <>
            {/* 添加话术 */}
            <div className="space-y-3">
              <div className="flex items-center justify-between">
                <Label>添加话术</Label>
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => setShowAIGenerator(!showAIGenerator)}
                >
                  <Sparkles className="h-4 w-4 mr-1" />
                  AI批量生成
                  {showAIGenerator ? (
                    <ChevronUp className="h-3 w-3 ml-1" />
                  ) : (
                    <ChevronDown className="h-3 w-3 ml-1" />
                  )}
                </Button>
              </div>

              {/* AI批量生成面板 */}
              <Collapsible open={showAIGenerator}>
                <CollapsibleContent>
                  <div className="space-y-3 p-4 border rounded-lg bg-gradient-to-br from-primary/5 to-primary/10">
                    <div className="flex items-center gap-2 mb-2">
                      <Sparkles className="h-4 w-4 text-primary" />
                      <span className="text-sm font-medium">AI智能生成话术</span>
                    </div>

                    <div className="grid grid-cols-2 gap-3">
                      <div className="space-y-2">
                        <Label className="text-xs">生成数量</Label>
                        <Select
                          value={aiGenerateCount.toString()}
                          onValueChange={value => setAiGenerateCount(Number(value))}
                        >
                          <SelectTrigger>
                            <SelectValue />
                          </SelectTrigger>
                          <SelectContent>
                            {[1,2,3, 5, 8, 10, 15, 20].map(num => (
                              <SelectItem key={num} value={num.toString()}>
                                {num} 条
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                      </div>

                      <div className="space-y-2">
                        <Label className="text-xs">每条字数</Label>
                        <Select
                          value={aiGenerateLength.toString()}
                          onValueChange={value => setAiGenerateLength(Number(value))}
                        >
                          <SelectTrigger>
                            <SelectValue />
                          </SelectTrigger>
                          <SelectContent>
                            {[30, 50, 80, 100, 150, 200, 300].map(num => (
                              <SelectItem key={num} value={num.toString()}>
                                约 {num} 字
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                      </div>
                    </div>

                    <div className="space-y-2">
                      <Label className="text-xs">生成风格（选填）</Label>
                      <Input
                        placeholder="例如：热情活泼、专业详细、简洁明了..."
                        value={aiGenerateStyle}
                        onChange={e => setAiGenerateStyle(e.target.value)}
                      />
                    </div>

                    <div className="space-y-2">
                      <Label className="text-xs">参考示例（选填，AI会仿写类似话术）</Label>
                      <Textarea
                        placeholder="输入一条示例话术，AI会生成相似风格的内容..."
                        value={aiGenerateExample}
                        onChange={e => setAiGenerateExample(e.target.value)}
                        className="min-h-[120px] resize-y"
                      />
                    </div>

                    <div className="flex gap-2">
                      <Button
                        onClick={handleAIGenerate}
                        disabled={isGenerating || (!aiGenerateStyle && !aiGenerateExample)}
                        className="flex-1"
                      >
                        <Sparkles className="h-4 w-4 mr-1" />
                        {isGenerating ? '生成中...' : `生成 ${aiGenerateCount} 条话术`}
                      </Button>
                      <Button
                        variant="outline"
                        onClick={() => {
                          setAiGenerateStyle('')
                          setAiGenerateExample('')
                        }}
                        disabled={isGenerating}
                      >
                        清空
                      </Button>
                    </div>

                    <p className="text-xs text-muted-foreground">
                      💡 提示：可在AI助手页面配置直播情景，让生成的话术更贴合场景
                    </p>
                  </div>
                </CollapsibleContent>
              </Collapsible>

              {/* 手动添加 */}
              <div className="flex gap-2">
                <Textarea
                  placeholder="手动输入直播话术内容，例如：欢迎来到直播间，今天给大家带来超值好物..."
                  value={newScript}
                  onChange={e => setNewScript(e.target.value)}
                  className="flex-1 min-h-[80px] resize-none"
                  onKeyDown={e => {
                    if (e.key === 'Enter' && e.ctrlKey) {
                      handleAddScript()
                    }
                  }}
                />
                <Button onClick={handleAddScript} className="self-end">
                  <Plus className="h-4 w-4 mr-1" />
                  添加
                </Button>
              </div>
              <p className="text-xs text-muted-foreground">
                提示：Ctrl + Enter 快速添加
              </p>
            </div>

            <Separator />

            {/* Tabs: 话术列表 / 播放队列 / 回收站 */}
            <Tabs defaultValue="scripts" className="w-full">
              <TabsList className="grid w-full grid-cols-3">
                <TabsTrigger value="scripts" className="flex items-center gap-2">
                  <MessageSquareText className="h-4 w-4" />
                  话术列表
                  <Badge variant="secondary" className="ml-1">
                    {scripts.length}
                  </Badge>
                </TabsTrigger>
                <TabsTrigger value="preview" className="flex items-center gap-2">
                  <Sparkles className="h-4 w-4" />
                  播放队列
                  <Badge variant="secondary" className="ml-1">
                    {previewQueue.length}
                  </Badge>
                </TabsTrigger>
                <TabsTrigger value="recycle" className="flex items-center gap-2">
                  <Trash className="h-4 w-4" />
                  回收站
                  <Badge variant="secondary" className="ml-1">
                    {recycleBin.length}
                  </Badge>
                </TabsTrigger>
              </TabsList>

              {/* 话术列表Tab */}
              <TabsContent value="scripts" className="mt-4 space-y-2">
                <div className="flex items-center justify-between">
                  <Label className="text-sm text-muted-foreground">
                    话术列表（点击播放按钮可测试效果）
                  </Label>
                  <div className="flex items-center gap-2">
                    <Label className="text-xs text-muted-foreground">播放顺序：</Label>
                    <Select
                      value={contentRewriteConfig.playback?.randomOrder ? 'random' : 'sequential'}
                      onValueChange={(value: string) => {
                        updateConfig({
                          contentRewrite: {
                            ...contentRewriteConfig,
                            playback: {
                              ...contentRewriteConfig.playback,
                              randomOrder: value === 'random',
                            },
                          },
                        })
                      }}
                    >
                      <SelectTrigger className="w-[100px] h-8">
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="sequential">顺序</SelectItem>
                        <SelectItem value="random">随机</SelectItem>
                      </SelectContent>
                    </Select>
                    <Badge variant="outline">
                      共 {scripts.length} 条
                    </Badge>
                  </div>
                </div>
                <ScrollArea className="h-[400px] rounded-md border p-3">
                {scripts.length === 0 ? (
                  <div className="text-center py-8 text-muted-foreground text-sm">
                    暂无话术，请先添加
                  </div>
                ) : (
                  <div className="space-y-2">
                    {scripts.map((script, index) => (
                      <div
                        key={script.id}
                        className="p-3 border rounded-lg bg-background hover:bg-accent/50 transition-colors"
                      >
                        <div className="flex items-start gap-3">
                          <Switch
                            checked={script.enabled}
                            onCheckedChange={checked =>
                              handleToggleScript(script.id, checked)
                            }
                            className="mt-1"
                          />
                          <div className="flex-1 min-w-0">
                            {editingId === script.id ? (
                              <div className="space-y-2">
                                <Textarea
                                  value={editingContent}
                                  onChange={e =>
                                    setEditingContent(e.target.value)
                                  }
                                  className="min-h-[60px] resize-none"
                                  autoFocus
                                />
                                <div className="flex gap-2">
                                  <Button
                                    size="sm"
                                    onClick={handleSaveEdit}
                                    variant="default"
                                  >
                                    <Check className="h-3 w-3 mr-1" />
                                    保存
                                  </Button>
                                  <Button
                                    size="sm"
                                    onClick={handleCancelEdit}
                                    variant="outline"
                                  >
                                    <X className="h-3 w-3 mr-1" />
                                    取消
                                  </Button>
                                </div>
                              </div>
                            ) : (
                              <>
                                <div className="flex items-center gap-2 mb-1">
                                  <Badge variant="outline" className="text-xs">
                                    #{index + 1}
                                  </Badge>
                                  {testPlayingScriptId === script.id && (
                                    <Badge className="text-xs">
                                      <Volume2 className="h-3 w-3 mr-1 animate-pulse" />
                                      播放中
                                    </Badge>
                                  )}
                                </div>
                                <p
                                  className={`text-sm whitespace-pre-wrap break-words ${
                                    !script.enabled && 'text-muted-foreground'
                                  }`}
                                >
                                  {script.content}
                                </p>
                              </>
                            )}
                          </div>
                          {editingId !== script.id && (
                            <div className="flex gap-1">
                              <Button
                                size="sm"
                                variant="ghost"
                                onClick={() => playDirectly(script.content, script.id)}
                                disabled={testPlayingScriptId === script.id}
                                className="h-8 w-8 p-0"
                                title="测试播放"
                              >
                                {testPlayingScriptId === script.id ? (
                                  <Volume2 className="h-3.5 w-3.5 animate-pulse" />
                                ) : (
                                  <Play className="h-3.5 w-3.5" />
                                )}
                              </Button>
                              <Button
                                size="sm"
                                variant="ghost"
                                onClick={() =>
                                  handleStartEdit(script.id, script.content)
                                }
                                className="h-8 w-8 p-0"
                              >
                                <Edit2 className="h-3.5 w-3.5" />
                              </Button>
                              <Button
                                size="sm"
                                variant="ghost"
                                onClick={() => handleDeleteScript(script.id)}
                                className="h-8 w-8 p-0 text-destructive hover:text-destructive"
                              >
                                <Trash2 className="h-3.5 w-3.5" />
                              </Button>
                            </div>
                          )}
                        </div>
                      </div>
                    ))}
                  </div>
                )}
              </ScrollArea>
              </TabsContent>

              {/* 播放队列Tab */}
              <TabsContent value="preview" className="mt-4 space-y-2">
                <div className="flex items-center justify-between">
                  <Label className="text-sm text-muted-foreground">
                    待播放内容队列（话术、报时、用户互动等）
                  </Label>
                  <div className="flex gap-2">
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={initializeQueue}
                      disabled={isPlaying || isLoadingQueue}
                    >
                      <RefreshCw className={`h-3.5 w-3.5 mr-1 ${isLoadingQueue ? 'animate-spin' : ''}`} />
                      刷新队列
                    </Button>
                    {isPlaying && (
                      <Badge variant="default" className="px-3 py-1.5">
                        <Volume2 className="h-3.5 w-3.5 mr-1 animate-pulse" />
                        播放中
                      </Badge>
                    )}
                  </div>
                </div>
                <ScrollArea className="h-[400px] rounded-md border p-3 bg-muted/20">
                  {isLoadingQueue && previewQueue.length === 0 ? (
                    <div className="text-center py-8 text-muted-foreground text-sm">
                      <RefreshCw className="h-8 w-8 mx-auto mb-3 animate-spin text-primary" />
                      <p className="mb-2">正在生成AI改写内容...</p>
                      <p className="text-xs">这可能需要几秒钟时间</p>
                    </div>
                  ) : previewQueue.length === 0 ? (
                    <div className="text-center py-8 text-muted-foreground text-sm">
                      <p className="mb-2">队列为空</p>
                      <p className="text-xs">请先在话术列表中添加并启用话术，然后点击"刷新队列"</p>
                    </div>
                  ) : (
                    <div className="space-y-2">
                      {previewQueue.map((item, index) => {
                        const isCurrentPlaying = currentPlayingId === item.id
                        // 如果有正在播放的，下一条是正在播放的下一个；否则下一条是第一个
                        const playingIndex = previewQueue.findIndex(i => i.id === currentPlayingId)
                        const nextIndex = playingIndex >= 0 ? playingIndex + 1 : 0
                        const isNext = index === nextIndex && index < previewQueue.length
                        
                        return (
                        <div
                          key={item.id}
                          className={`p-3 border rounded-lg transition-all duration-300 ${
                            isCurrentPlaying
                              ? 'bg-blue-50 dark:bg-blue-950/20 border-blue-500 scale-[1.02] shadow-lg'
                              : isNext
                              ? 'bg-gradient-to-r from-primary/10 to-primary/5 border-l-4 border-primary'
                              : 'bg-background hover:bg-accent/50'
                          }`}
                        >
                          <div className="space-y-2">
                            <div className="flex items-center gap-2 flex-wrap">
                              {/* 类型标签 */}
                              <Badge 
                                variant={
                                  item.type === 'live_script' ? 'outline' : 
                                  item.type === 'time_announcement' ? 'secondary' :
                                  item.type === 'quick_broadcast' ? 'default' :
                                  item.type === 'user_interaction' ? 'default' : 'destructive'
                                }
                                className="text-xs"
                              >
                                {item.type === 'live_script' ? '📝 话术' : 
                                 item.type === 'time_announcement' ? '⏰ 报时' :
                                 item.type === 'quick_broadcast' ? '👋 一键播报' :
                                 item.type === 'user_interaction' ? '💬 自动互动' : '🤖 AI回复'}
                              </Badge>
                              
                              {/* 播放状态标签 */}
                              {isCurrentPlaying ? (
                                <Badge className="text-xs bg-blue-500">
                                  <Volume2 className="h-3 w-3 mr-1 animate-pulse" />
                                  正在播放
                                </Badge>
                              ) : isNext ? (
                                <>
                                  <Badge variant="default" className="text-xs">
                                    下一条
                                  </Badge>
                                  {countdown > 0 && !currentPlayingId && (
                                    <Badge variant="secondary" className="text-xs animate-pulse">
                                      <Timer className="h-3 w-3 mr-1" />
                                      {countdown}秒后播放
                                    </Badge>
                                  )}
                                </>
                              ) : (
                                <Badge variant="outline" className="text-xs">
                                  队列 {index + 1}
                                </Badge>
                              )}
                            </div>
                            {/* 只有话术类型才显示原话术和AI改写 */}
                            {item.type === 'live_script' ? (
                              <>
                                <div className="space-y-1">
                                  <div className="flex items-center justify-between">
                                    <p className="text-xs text-muted-foreground">原话术：</p>
                                    <Badge variant="outline" className="text-xs">
                                      {item.originalContent.length}字
                                    </Badge>
                                  </div>
                                  <p className="text-sm whitespace-pre-wrap break-words">{item.originalContent}</p>
                                </div>
                                <div className="space-y-1">
                                  <div className="flex items-center justify-between">
                                    <p className="text-xs text-muted-foreground">AI改写：</p>
                                    <Badge variant="outline" className="text-xs">
                                      {item.rewrittenContent.length}字
                                    </Badge>
                                  </div>
                                  <p className="text-sm font-medium whitespace-pre-wrap break-words">{item.rewrittenContent}</p>
                                </div>
                              </>
                            ) : (
                              <div className="space-y-1">
                                <div className="flex items-center justify-between">
                                  <p className="text-xs text-muted-foreground">播放内容：</p>
                                  <Badge variant="outline" className="text-xs">
                                    {item.rewrittenContent.length}字
                                  </Badge>
                                </div>
                                <p className="text-sm font-medium whitespace-pre-wrap break-words">{item.rewrittenContent}</p>
                              </div>
                            )}
                          </div>
                        </div>
                        )
                      })}
                    </div>
                  )}
                </ScrollArea>
                <div className="space-y-1">
                  <p className="text-xs text-muted-foreground">
                    💡 队列说明：显示待播放的话术内容，优先播放队列顶部内容
                  </p>
                  <p className="text-xs text-muted-foreground">
                    ⚙️ 播放间隔：{globalPlayback?.interval?.min || 3}-{globalPlayback?.interval?.max || 10}秒
                  </p>
                  <p className="text-xs text-muted-foreground">
                    🎯 播放优先级：AI智能回复 {'>'} 用户互动/一键播报 {'>'} 话术队列
                  </p>
                </div>
              </TabsContent>

              {/* 回收站Tab */}
              <TabsContent value="recycle" className="mt-4 space-y-2">
                <div className="flex items-center justify-between">
                  <Label className="text-sm text-muted-foreground">
                    已播放的历史记录
                  </Label>
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => setRecycleBin([])}
                    disabled={recycleBin.length === 0}
                  >
                    <Trash className="h-3.5 w-3.5 mr-1" />
                    清空
                  </Button>
                </div>
                <ScrollArea className="h-[400px] rounded-md border p-3">
                  {recycleBin.length === 0 ? (
                    <div className="text-center py-8 text-muted-foreground text-sm">
                      暂无播放记录
                    </div>
                  ) : (
                    <div className="space-y-2">
                      {recycleBin.map((item) => (
                        <div
                          key={item.id}
                          className="p-3 border rounded-lg bg-background hover:bg-accent/30 transition-colors"
                        >
                          <div className="space-y-2">
                            <div className="flex items-center justify-between">
                              <Badge variant="outline" className="text-xs">
                                {new Date(item.playedAt).toLocaleString()}
                              </Badge>
                            </div>
                            <div className="space-y-1">
                              <div className="flex items-center justify-between">
                                <p className="text-xs text-muted-foreground">原话术：</p>
                                <Badge variant="outline" className="text-xs">
                                  {item.originalContent.length}字
                                </Badge>
                              </div>
                              <p className="text-sm whitespace-pre-wrap break-words">{item.originalContent}</p>
                            </div>
                            <div className="space-y-1">
                              <div className="flex items-center justify-between">
                                <p className="text-xs text-muted-foreground">AI改写：</p>
                                <Badge variant="outline" className="text-xs">
                                  {item.rewrittenContent.length}字
                                </Badge>
                              </div>
                              <p className="text-sm whitespace-pre-wrap break-words">{item.rewrittenContent}</p>
                            </div>
                          </div>
                        </div>
                      ))}
                    </div>
                  )}
                </ScrollArea>
              </TabsContent>
            </Tabs>

            <Separator />

            {/* 一键播报 */}
            <div className="space-y-3">
              <div className="flex items-center justify-between">
                <Label className="flex items-center gap-2">
                  <Sparkles className="h-4 w-4" />
                  一键播报
                </Label>
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => setShowTemplateConfig(true)}
                  className="h-8"
                >
                  <Settings className="h-3.5 w-3.5 mr-1" />
                  模板配置
                </Button>
              </div>
              
              {/* 播放模式选择 */}
              <div className="space-y-2">
                <Label className="text-sm">播放模式（一键播报）</Label>
                <Select
                  value={quickPlayMode}
                  onValueChange={(value: 'immediate' | 'next') => setQuickPlayMode(value)}
                >
                  <SelectTrigger className="h-9">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="immediate">立即播放（打断当前）</SelectItem>
                    <SelectItem value="next">等待播放完成</SelectItem>
                  </SelectContent>
                </Select>
                <p className="text-xs text-muted-foreground">
                  一键播报是手动触发的，可以选择立即播放或等待当前内容播放完成
                </p>
              </div>
              
              <div className="grid grid-cols-2 gap-2">
                <Button
                  variant="outline"
                  onClick={() => handleQuickTimeAnnouncement(false)}
                  className="flex items-center gap-2"
                >
                  <Timer className="h-4 w-4" />
                  报时
                </Button>
                <Button
                  variant="outline"
                  onClick={() => handleQuickUserInteraction(false)}
                  className="flex items-center gap-2"
                >
                  <UserPlus className="h-4 w-4" />
                  用户互动
                </Button>
              </div>
              
              <p className="text-xs text-muted-foreground">
                💡 提示：点击"模板配置"自定义播报内容
              </p>
            </div>

            {/* 提示信息 */}
            <div className="text-xs text-muted-foreground p-3 bg-muted/30 rounded-md">
              <p className="font-medium mb-1">使用说明：</p>
              <ul className="space-y-1 list-disc list-inside">
                <li><strong>话术列表：</strong>添加和管理直播话术，AI会自动改写后播放</li>
                <li><strong>播放队列：</strong>显示待播放的内容，包括话术、报时、用户互动等</li>
                <li><strong>回收站：</strong>查看已播放的话术历史记录</li>
                <li><strong>一键播报：</strong>手动触发报时和用户互动播报，播放模式可独立配置</li>
                <li><strong>自动播报：</strong>在全局设置中配置自动检测用户互动的播放模式</li>
                <li><strong>播放优先级：</strong>AI智能回复 {'>'} 用户互动/一键播报 {'>'} 话术队列</li>
                <li><strong>停止任务：</strong>停止播放时会清理所有定时器和播放状态</li>
              </ul>
            </div>
          </>
        )}
          </CardContent>
        </CollapsibleContent>
      </Collapsible>
    </Card>

      {/* 模板配置对话框 */}
      <Dialog open={showTemplateConfig} onOpenChange={setShowTemplateConfig}>
        <DialogContent className="max-w-2xl max-h-[80vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>播报模板配置</DialogTitle>
            <DialogDescription>
              快速播报：点击按钮快速播报内容。更多配置请前往"全局设置"。
            </DialogDescription>
          </DialogHeader>
          
          <div className="space-y-6 py-4">
            {/* 报时模板配置 */}
            <div className="space-y-3">
              <div className="flex items-center justify-between">
                <Label className="text-base font-semibold flex items-center gap-2">
                  <Timer className="h-4 w-4" />
                  报时模板
                </Label>
                <Select
                  value={globalPlayback?.timeAnnouncement?.mode || 'random'}
                  onValueChange={(value: 'random' | 'sequential') =>
                    updateConfig({
                      playback: {
                        ...globalPlayback,
                        timeAnnouncement: {
                          ...globalPlayback.timeAnnouncement!,
                          mode: value,
                        },
                      },
                    })
                  }
                >
                  <SelectTrigger className="w-[140px]">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="random">随机播放</SelectItem>
                    <SelectItem value="sequential">顺序播放</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              
              <div className="space-y-2">
                <Label className="text-sm">模板列表（每行一个，使用 {'{时间}'} 作为占位符）</Label>
                <Textarea
                  value={(globalPlayback?.timeAnnouncement?.templates || []).join('\n')}
                  onChange={e =>
                    updateConfig({
                      playback: {
                        ...globalPlayback,
                        timeAnnouncement: {
                          ...globalPlayback.timeAnnouncement!,
                          templates: e.target.value.split('\n'),
                        },
                      },
                    })
                  }
                  placeholder="示例：&#10;当前时间{时间}&#10;现在是{时间}&#10;时间过得真快，一眨眼就来到了{时间}&#10;不知不觉已经{时间}了"
                  className="min-h-[120px] resize-none font-mono text-sm"
                />
                <div className="bg-muted/30 rounded-md p-3 space-y-2">
                  <p className="text-xs font-medium">📝 配置示例：</p>
                  <div className="space-y-1 text-xs text-muted-foreground font-mono">
                    <div>当前时间{'{时间}'}</div>
                    <div>现在是{'{时间}'}</div>
                    <div>时间过得真快，一眨眼就来到了{'{时间}'}</div>
                    <div>不知不觉已经{'{时间}'}了</div>
                    <div>让我看看现在几点了，哦，{'{时间}'}了</div>
                  </div>
                </div>
              </div>
            </div>

            <Separator />

            {/* 用户互动模板配置（快捷入口，直接修改全局设置） */}
            <div className="space-y-4">
              <div className="flex items-center justify-between">
                <div>
                  <Label className="text-base font-semibold flex items-center gap-2">
                    <MessageSquareText className="h-4 w-4" />
                    用户互动模板
                  </Label>
                  <p className="text-xs text-muted-foreground mt-1">
                    此处为全局设置的快捷入口，修改后会同步到全局设置
                  </p>
                </div>
                <Select
                  value={globalPlayback?.userInteraction?.mode || 'random'}
                  onValueChange={(value: 'random' | 'sequential') =>
                    updateConfig({
                      playback: {
                        ...globalPlayback,
                        userInteraction: {
                          ...globalPlayback.userInteraction!,
                          mode: value,
                        },
                      },
                    })
                  }
                >
                  <SelectTrigger className="w-[140px]">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="random">随机播放</SelectItem>
                    <SelectItem value="sequential">顺序播放</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              
              <Tabs defaultValue="room_enter" className="w-full">
                <TabsList className="grid w-full grid-cols-3">
                  <TabsTrigger value="room_enter" className="text-xs">进入直播间</TabsTrigger>
                  <TabsTrigger value="room_like" className="text-xs">点赞</TabsTrigger>
                  <TabsTrigger value="room_follow" className="text-xs">关注</TabsTrigger>
                </TabsList>
                <TabsList className="grid w-full grid-cols-3 mt-2">
                  <TabsTrigger value="subscribe_merchant_brand_vip" className="text-xs">品牌会员</TabsTrigger>
                  <TabsTrigger value="live_order" className="text-xs">购买商品</TabsTrigger>
                  <TabsTrigger value="ecom_fansclub_participate" className="text-xs">粉丝团</TabsTrigger>
                </TabsList>
                
                {/* 进入直播间 */}
                <TabsContent value="room_enter" className="space-y-2 mt-3">
                  <Label className="text-sm">进入直播间模板（每行一个）</Label>
                  <Textarea
                    value={(globalPlayback?.userInteraction?.templates?.room_enter || []).join('\n')}
                    onChange={e =>
                      updateConfig({
                        playback: {
                          ...globalPlayback,
                          userInteraction: {
                            ...globalPlayback.userInteraction!,
                            templates: {
                              ...globalPlayback.userInteraction!.templates,
                              room_enter: e.target.value.split('\n'),
                            },
                          },
                        },
                      })
                    }
                    placeholder="欢迎{用户}来到直播间&#10;欢迎{用户}的到来&#10;{用户}来啦，大家欢迎"
                    className="min-h-[100px] resize-none font-mono text-xs"
                  />
                </TabsContent>
                
                {/* 点赞 */}
                <TabsContent value="room_like" className="space-y-2 mt-3">
                  <Label className="text-sm">点赞直播模板（每行一个）</Label>
                  <Textarea
                    value={(globalPlayback?.userInteraction?.templates?.room_like || []).join('\n')}
                    onChange={e =>
                      updateConfig({
                        playback: {
                          ...globalPlayback,
                          userInteraction: {
                            ...globalPlayback.userInteraction!,
                            templates: {
                              ...globalPlayback.userInteraction!.templates,
                              room_like: e.target.value.split('\n'),
                            },
                          },
                        },
                      })
                    }
                    placeholder="感谢{用户}的点赞&#10;谢谢{用户}点赞支持&#10;{用户}点赞了，谢谢支持"
                    className="min-h-[100px] resize-none font-mono text-xs"
                  />
                </TabsContent>
                
                {/* 关注 */}
                <TabsContent value="room_follow" className="space-y-2 mt-3">
                  <Label className="text-sm">关注直播间模板（每行一个）</Label>
                  <Textarea
                    value={(globalPlayback?.userInteraction?.templates?.room_follow || []).join('\n')}
                    onChange={e =>
                      updateConfig({
                        playback: {
                          ...globalPlayback,
                          userInteraction: {
                            ...globalPlayback.userInteraction!,
                            templates: {
                              ...globalPlayback.userInteraction!.templates,
                              room_follow: e.target.value.split('\n'),
                            },
                          },
                        },
                      })
                    }
                    placeholder="感谢{用户}的关注&#10;欢迎{用户}关注直播间&#10;谢谢{用户}关注"
                    className="min-h-[100px] resize-none font-mono text-xs"
                  />
                </TabsContent>
                
                {/* 品牌会员 */}
                <TabsContent value="subscribe_merchant_brand_vip" className="space-y-2 mt-3">
                  <Label className="text-sm">品牌会员模板（每行一个）</Label>
                  <Textarea
                    value={(globalPlayback?.userInteraction?.templates?.subscribe_merchant_brand_vip || []).join('\n')}
                    onChange={e =>
                      updateConfig({
                        playback: {
                          ...globalPlayback,
                          userInteraction: {
                            ...globalPlayback.userInteraction!,
                            templates: {
                              ...globalPlayback.userInteraction!.templates,
                              subscribe_merchant_brand_vip: e.target.value.split('\n'),
                            },
                          },
                        },
                      })
                    }
                    placeholder="欢迎{用户}加入品牌会员&#10;感谢{用户}成为品牌会员&#10;{用户}加入了品牌会员，感谢支持"
                    className="min-h-[100px] resize-none font-mono text-xs"
                  />
                </TabsContent>
                
                {/* 购买商品 */}
                <TabsContent value="live_order" className="space-y-2 mt-3">
                  <Label className="text-sm">购买商品模板（每行一个，支持{'{用户}'}和{'{商品}'}占位符）</Label>
                  <Textarea
                    value={(globalPlayback?.userInteraction?.templates?.live_order || []).join('\n')}
                    onChange={e =>
                      updateConfig({
                        playback: {
                          ...globalPlayback,
                          userInteraction: {
                            ...globalPlayback.userInteraction!,
                            templates: {
                              ...globalPlayback.userInteraction!.templates,
                              live_order: e.target.value.split('\n'),
                            },
                          },
                        },
                      })
                    }
                    placeholder="感谢{用户}购买{商品}&#10;谢谢{用户}的订单&#10;{用户}购买了{商品}，感谢支持"
                    className="min-h-[100px] resize-none font-mono text-xs"
                  />
                </TabsContent>
                
                {/* 粉丝团 */}
                <TabsContent value="ecom_fansclub_participate" className="space-y-2 mt-3">
                  <Label className="text-sm">粉丝团模板（每行一个）</Label>
                  <Textarea
                    value={(globalPlayback?.userInteraction?.templates?.ecom_fansclub_participate || []).join('\n')}
                    onChange={e =>
                      updateConfig({
                        playback: {
                          ...globalPlayback,
                          userInteraction: {
                            ...globalPlayback.userInteraction!,
                            templates: {
                              ...globalPlayback.userInteraction!.templates,
                              ecom_fansclub_participate: e.target.value.split('\n'),
                            },
                          },
                        },
                      })
                    }
                    placeholder="欢迎{用户}加入粉丝团&#10;感谢{用户}加入粉丝团&#10;{用户}加入粉丝团啦，谢谢支持"
                    className="min-h-[100px] resize-none font-mono text-xs"
                  />
                </TabsContent>
              </Tabs>
              
              <div className="bg-blue-50 dark:bg-blue-950/30 rounded-md p-3 border border-blue-200 dark:border-blue-900">
                <p className="text-xs text-blue-700 dark:text-blue-300">
                  💡 提示：这些模板与"全局设置 → 播放配置 → 用户互动播报 → 互动类型模板"完全同步。在这里修改会同步到全局设置，反之亦然。
                </p>
              </div>
            </div>
          </div>
        </DialogContent>
      </Dialog>
    </>
  )
}
